package com.xjscrm.console.service.customer.list.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.CacheKey;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.MerConfigKeyEnum;
import com.xjscrm.common.enums.MerConfigTypeEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.console.mapper.MerBaseConfigMapper;
import com.xjscrm.console.mapper.WhiteListMapper;
import com.xjscrm.console.mapper.WwCustomerBlackwhitelistLogMapper;
import com.xjscrm.console.mapper.WwCustomerMapper;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.list.BatchDeleListDto;
import com.xjscrm.console.param.list.KickingLanguageSkillDto;
import com.xjscrm.console.param.list.WwCustomerListQuery;
import com.xjscrm.console.param.list.WwCustomerWhiteDto;
import com.xjscrm.console.param.user.ChildMerchatDto;
import com.xjscrm.console.service.common.user.UserService;
import com.xjscrm.console.service.customer.childUser.ChildMerchatService;
import com.xjscrm.console.service.customer.list.WhiteListService;
import com.xjscrm.console.vo.MyPageInfo;
import com.xjscrm.console.vo.WwCustomerBlackVo;
import com.xjscrm.console.vo.WwCustomerWhiteVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WhiteListServiceImpl implements WhiteListService {

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WhiteListMapper whiteListMapper;

    @Autowired
    private WwCustomerBlackwhitelistLogMapper wwCustomerBlackwhitelistLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    @Autowired
    private ChildMerchatService childMerchatService;

    @Autowired
    private UserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWhileList(WwCustomerWhiteDto wwCustomerWhiteDto) {
        if(wwCustomerWhiteDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(wwCustomerWhiteDto.getWxid()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "微信ID为空");
        }
        if(wwCustomerWhiteDto.getOperatorType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //主账号
        if(wwCustomerWhiteDto.getOperatorType()==0){
            wwCustomerWhiteDto.setOperatorId(wwCustomerWhiteDto.getMerId());
        }
        //子账号
        if(wwCustomerWhiteDto.getOperatorType()==1){
            wwCustomerWhiteDto.setOperatorId(wwCustomerWhiteDto.getChildId());
        }

        WwCustomerWhitelist wwCustomerWhitelist=new WwCustomerWhitelist();
        BeanUtil.copyProperties(wwCustomerWhiteDto,wwCustomerWhitelist);

        WwCustomer wwCustomer= wwCustomerMapper.getByWxId(wwCustomerWhitelist.getWxid(),wwCustomerWhitelist.getMerId());
        if(wwCustomer==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该客户");
        }

        //添加白名单
        wwCustomerWhitelist.setName(wwCustomer.getName());
        wwCustomerWhitelist.setHeadImg(wwCustomer.getHeadImgUrl());
        whiteListMapper.addwwCustomerWhitelist(wwCustomerWhitelist);

        //添加日志
        WwCustomerBlackwhitelistLog wwCustomerBlackwhitelistLog=new WwCustomerBlackwhitelistLog();
        BeanUtil.copyProperties(wwCustomerWhitelist,wwCustomerBlackwhitelistLog);
        wwCustomerBlackwhitelistLog.setType(1);
        wwCustomerBlackwhitelistLog.setOpt(0);
        wwCustomerBlackwhitelistLogMapper.addWwCustomerBlackwhitelistLog(wwCustomerBlackwhitelistLog);

    }


    @Override
    public Object getWhiteList(WwCustomerListQuery wwCustomerListQuery) {
        if(wwCustomerListQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(wwCustomerListQuery.getOrderByField(), wwCustomerListQuery.isAsc());
        PageHelper.startPage(wwCustomerListQuery.getCurrent(),wwCustomerListQuery.getSize(),orderBy);
        List<WwCustomerWhiteVo> wwCustomerWhiteVoList= whiteListMapper.getWhiteList(wwCustomerListQuery);
        if(wwCustomerWhiteVoList==null){
            return new MyPageInfo<>(null);
        }
        for (WwCustomerWhiteVo wwCustomerWhiteVo:wwCustomerWhiteVoList) {
            try {
                if(wwCustomerWhiteVo.getOperatorType()==0){
                    BaseDto baseDto=new BaseDto();
                    baseDto.setMerId(wwCustomerWhiteVo.getOperatorId());
                    Merchant merchant = userService.getById(baseDto);
                    wwCustomerWhiteVo.setOperatorName(merchant.getUserName());
                }

                if(wwCustomerWhiteVo.getOperatorType()==1){
                    ChildMerchatDto childMerchatDto=new ChildMerchatDto();
                    childMerchatDto.setMerId(wwCustomerWhiteVo.getMerId());
                    childMerchatDto.setId(wwCustomerWhiteVo.getOperatorId());
                    MerchatChild merchatChild = childMerchatService.getById(childMerchatDto);
                    wwCustomerWhiteVo.setOperatorName(merchatChild.getUserName());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        MyPageInfo<WwCustomerWhiteVo> pageInfo = new MyPageInfo<>(wwCustomerWhiteVoList);
        return pageInfo;
    }

    @Override
    public void deleBlackList(BatchDeleListDto batchDeleListDto) {
        if(batchDeleListDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchDeleListDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwCustomerWhitelist wwCustomerWhitelist=whiteListMapper.getById(batchDeleListDto.getId(),batchDeleListDto.getMerId());

        if(wwCustomerWhitelist==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该白名单不存在");
        }

        //添加日志
        WwCustomerBlackwhitelistLog wwCustomerBlackwhitelistLog=new WwCustomerBlackwhitelistLog();
        BeanUtil.copyProperties(wwCustomerWhitelist,wwCustomerBlackwhitelistLog);
        wwCustomerBlackwhitelistLog.setType(1);
        wwCustomerBlackwhitelistLog.setOpt(1);
        wwCustomerBlackwhitelistLogMapper.addWwCustomerBlackwhitelistLog(wwCustomerBlackwhitelistLog);

        //删除白名单
        whiteListMapper.deleById(batchDeleListDto.getId(),batchDeleListDto.getMerId());
    }


    @Override
    public void addKickingLanguageSkill(KickingLanguageSkillDto languageSkillDto) {
        if(languageSkillDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(languageSkillDto.getWords())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(languageSkillDto.getMerId(), MerConfigKeyEnum.KICKING_LANGUAGE_SKILL_CONFIG.getValue());
        if(merBaseConfig==null){
            int now = DateUtil.getTime();
            MerBaseConfig merBaseConfig1 = new MerBaseConfig();
            merBaseConfig1.setId(IdWorker.getId());
            merBaseConfig1.setMerId(languageSkillDto.getMerId());
            merBaseConfig1.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig1.setKey(MerConfigKeyEnum.KICKING_LANGUAGE_SKILL_CONFIG.getValue());
            merBaseConfig1.setVal(languageSkillDto.getWords());
            merBaseConfig1.setCreateTime(now);
            merBaseConfig1.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig1);
        }else {
            merBaseConfig.setVal(languageSkillDto.getWords());
            merBaseConfigMapper.update(merBaseConfig);
        }

        //插入缓存
        String key = String.format(CacheKey.KICKING_LANGUAGE_SKILL_CACHE, languageSkillDto.getMerId());
        redisTemplate.opsForValue().set(key,languageSkillDto.getWords());

    }

    @Override
    public Object getKickingLanguageSkill(BaseDto baseDto) {

        if(baseDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String key = String.format(CacheKey.KICKING_LANGUAGE_SKILL_CACHE, baseDto.getMerId());
        if(redisTemplate.hasKey(key)){
            return redisTemplate.opsForValue().get(key);
        }else {
            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(baseDto.getMerId(), MerConfigKeyEnum.KICKING_LANGUAGE_SKILL_CONFIG.getValue());
            if(merBaseConfig!=null){
                redisTemplate.opsForValue().set(key,merBaseConfig.getVal());
                return merBaseConfig.getVal();
            }else {
               return null;
            }
        }

    }
}
